package com.sz.app.oss.api.common.csr;

import com.sz.app.oss.constants.Permissions;
import com.sz.biz.csr.entity.CsrAskBoardDetail;
import com.sz.biz.csr.dto.CsrAskBoardDetailDto;
import com.sz.biz.csr.dto.CsrAskBoardSchemaDto;
import com.sz.biz.csr.service.CsrAskBoardDetailService;
import com.sz.biz.csr.service.CsrAskBoardSchemaService;
import com.sz.biz.app.web.BaseController;
import com.sz.biz.common.constants.MessagesCodes;
import com.sz.common.base.dto.QResultDto;
import com.sz.common.base.dto.ResultDto;
import com.sz.common.base.exception.BizException;
import com.sz.common.base.exception.Exceptions;
import com.sz.common.base.utils.StringUtils;
import com.sz.biz.logistics.constants.ErrorCodes;
import com.sz.common.core.service.PrincipalUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.map.HashedMap;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by xutao on 17/5/15.
 */
@RestController
@RequestMapping("/api/v1/csraskboard")
@Api(description = " ", tags = "040-001、客服-留言板")
public class CsrAskBoardController extends BaseController {

    @Autowired
    CsrAskBoardSchemaService csrAskBoardSchemaService;

    @Autowired
    CsrAskBoardDetailService csrAskBoardDetailService;

    /**
     * 获取运营端留言板主页列表
     *
     * @throws BizException ex
     */
    @ApiOperation(value = "获取运营端留言板主页列表", notes = "获取运营端留言板主页列表，支持分页")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "q", value = "查询的关键字", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "sortName", value = "查询的关键字", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "isAsc", value = "排序类型,true为升序，false为降序", required = false, dataType = "boolean", paramType = "query"),
            @ApiImplicitParam(name = "pageIndex", value = "分页 默认第一页", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "页面大小", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "beginTime", value = "开始时间", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "endTime", value = "结束时间", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "customerId", value = "客户id", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "status", value = "留言状态", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "customerName", value = "客户姓名", dataType = "string", paramType = "query")
    })
    @RequestMapping(value = "/search", method = {RequestMethod.GET})
    public QResultDto getOperationPointList(@RequestParam(defaultValue = "") String q,
                                            @RequestParam(defaultValue = "content") String sortName,
                                            @RequestParam(required = false, defaultValue = "true") boolean isAsc,
                                            @RequestParam(defaultValue = "1") int pageIndex,
                                            @RequestParam(name = "pageSize", defaultValue = "10") int pageSize,
                                            @RequestParam(required = false) String beginTime,
                                            @RequestParam(required = false) String endTime,
                                            @RequestParam(defaultValue = "0") int customerId,
                                            @RequestParam(defaultValue = "0") int status,
                                            @RequestParam(required = false) String customerName) throws BizException {

        q = StringUtils.replaceSqlPattern(q);
        beginTime = StringUtils.replaceSqlPattern(beginTime);
        endTime = StringUtils.replaceSqlPattern(endTime);
        if (StringUtils.isEmpty(beginTime)) {
            beginTime = null;
        }
        if (StringUtils.isEmpty(endTime)) {
            endTime = null;
        }
        //fix LOGP-1882
        customerName = StringUtils.isEmpty(customerName) ? null : StringUtils.replaceSqlPattern(customerName);
        Date beginDate = null;
        Date endDate = null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (beginTime != null && !"".equalsIgnoreCase(beginTime)) {
            try {
                beginDate = sdf.parse(beginTime);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        if (endTime != null && !"".equalsIgnoreCase(endTime)) {
            try {
                endDate = sdf.parse(endTime);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }

        QResultDto qResultDto = csrAskBoardSchemaService.getAskBoardSchemaList(q, pageIndex, pageSize, sortName, isAsc,
                null, beginDate, endDate, customerId, status, customerName);
        return qResultDto;
    }

    /**
     * 获取留言聊天记录
     *
     * @throws BizException ex
     */
    @ApiOperation(value = "获取留言聊天记录", notes = "获取留言聊天记录，支持分页")
    @ApiImplicitParams(
            {@ApiImplicitParam(name = "pageSize", value = "页面大小", dataType = "int", paramType = "query"),
                    @ApiImplicitParam(name = "pageIndex", value = "页面索引", dataType = "int", paramType = "query"),
                    @ApiImplicitParam(name = "refAskBoardId", value = "关联的会话ID", dataType = "int", paramType = "query")
            })
    @RequiresPermissions(value = {Permissions.BIZ_MGT_BASE_CSR_MESSAGE, Permissions.BIZ_MGT_BASE_CSR_WORK_ORDER}, logical = Logical.OR)
    @RequestMapping(value = "/historylist", method = {RequestMethod.GET})
    public QResultDto getHistoryList(@RequestParam(name = "pageSize", defaultValue = "10") int pageSize,
                                     @RequestParam(name = "pageIndex", defaultValue = "1") int pageIndex,
                                     @RequestParam(name = "refAskBoardId", defaultValue = "0") int refAskBoardId) throws BizException {
        QResultDto qResultDto = csrAskBoardDetailService.getHistoryList(pageSize, pageIndex, refAskBoardId);
        return qResultDto;
    }

    /**
     * 留言
     */
    @ApiOperation(value = "留言", notes = "留言")
    @RequiresPermissions(Permissions.BIZ_MGT_BASE_CSR_MESSAGE)
    @RequestMapping(value = "/leavemessage", method = {RequestMethod.POST})
    public QResultDto leaveMessage(@RequestBody @Validated CsrAskBoardDetail csrAskBoardDetail) throws BizException {
        String messageBody = csrAskBoardDetail.getMessageBody();
        messageBody = messageBody.replaceAll("[\ud800\udc00-\udbff\udfff\ud800-\udfff]", "");
        csrAskBoardDetail.setMessageBody(messageBody);
        QResultDto qResultDto = new QResultDto();
        CsrAskBoardDetailDto resObj = csrAskBoardDetailService.save(csrAskBoardDetail);
        qResultDto.setData(resObj);
        return qResultDto;
    }

    /**
     * done掉留言
     */
    @ApiOperation(value = "done掉留言", notes = "done掉留言")
    @RequiresPermissions(Permissions.BIZ_MGT_BASE_CSR_MESSAGE)
    @RequestMapping(value = "/doneleavemessage/{id}", method = {RequestMethod.PUT})
    public QResultDto doneLeaveMessage(@PathVariable Integer id) throws BizException {
        QResultDto qResultDto = new QResultDto();
        csrAskBoardSchemaService.doneCsrAskBoardById(id);
        qResultDto.setData(id);
        return qResultDto;
    }

    /**
     * 获取code列表
     */
    @ApiOperation(value = "获取code列表", notes = "获取code列表，支持分页")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "q", value = "查询的关键字",
                    dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "sortName", value = "查询的关键字",
                    dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "isAsc", value = "排序类型,true为升序，false为降序", required = false,
                    dataType = "boolean", paramType = "query"),
            @ApiImplicitParam(name = "pageIndex", value = "分页 默认第一页",
                    dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "页面大小",
                    dataType = "int", paramType = "query")})
    @RequiresPermissions(Permissions.BIZ_MGT_BASE_CSR_MESSAGE)
    @RequestMapping(value = "/codelist", method = {RequestMethod.GET})
    public QResultDto getCodeList(@RequestParam(defaultValue = "") String q,
                                  @RequestParam(defaultValue = "code") String sortName,
                                  @RequestParam(required = false, defaultValue = "true") boolean isAsc,
                                  @RequestParam(defaultValue = "1") int pageIndex,
                                  @RequestParam(name = "pageSize", defaultValue = "10") int pageSize) throws BizException {

        return csrAskBoardSchemaService.getCodeList(q, pageIndex, pageSize, sortName, isAsc, null);
    }

    /**
     * 异步检查code是否存在
     */
    @ApiOperation(value = "异步检查code是否存在", notes = "异步检查code是否存在")
    @RequestMapping(value = "/check/{code}", method = {RequestMethod.GET})
    public QResultDto addWorkOrder(@PathVariable String code) throws Exception {
        CsrAskBoardSchemaDto csrAskBoardSchemaDto = csrAskBoardSchemaService.checkCodeExist(code);
        QResultDto qResultDto = new QResultDto();
        if (csrAskBoardSchemaDto == null) {
            throw Exceptions.bizException(ErrorCodes.ERROR_WORK_ORDER_ASK_CODE_NOT_EXISTS);
        } else {
            qResultDto.setData(csrAskBoardSchemaDto);
        }
        return qResultDto;
    }

    /**
     * 删除留言
     *
     * @param listId
     * @throws Exception
     */
    @ApiOperation(value = "删除留言", notes = "删除留言")
    @ApiImplicitParam(name = "listId", value = "工单ID", required = true, dataType = "List", paramType = "body")
    @RequiresPermissions(Permissions.BIZ_MGT_BASE_CSR_MESSAGE)
    @RequestMapping(value = "deletions", method = {RequestMethod.POST})
    public ResultDto deleteExchangeRate(@RequestBody List<Integer> listId) {
        csrAskBoardSchemaService.batchDelete(listId);
        ResultDto qResultDto = getOperateSuccessDto(MessagesCodes.MODULE_CSR_ASK_BOARD_DELETE_SUCCESS);
        return qResultDto;
    }

    /**
     * 获取未读消息条数
     */
    @ApiOperation(value = "获取未读消息条数", notes = "获取未读消息条数")
    @RequiresPermissions(Permissions.BIZ_MGT_BASE_CSR_MESSAGE)
    @RequestMapping(value = "/unreadcount", method = {RequestMethod.GET})
    public QResultDto getUnReadCount() throws BizException {
        QResultDto qResultDto = new QResultDto();
        int count = csrAskBoardSchemaService.getUnReadCount(PrincipalUtils.getAccountId());
        Map<String,Object> map = new HashedMap();
        map.put("unReadCount", count);
        qResultDto.setData(map);
        return qResultDto;
    }

    /**
     * 标记留言无未读消息
     *
     * @param listId
     * @throws Exception
     */
    @ApiOperation(value = "标记留言无未读消息", notes = "标记留言无未读消息")
    @ApiImplicitParam(name = "listId", value = "留言板主ID list", required = true, dataType = "List", paramType = "body")
    @RequiresPermissions(Permissions.BIZ_MGT_BASE_CSR_MESSAGE)
    @RequestMapping(value = "/flagforread", method = {RequestMethod.POST})
    public QResultDto flagForRead(@RequestBody List<Integer> listId) {
        csrAskBoardSchemaService.flagForRead(listId);
        return new QResultDto();
    }
}
